<template>
  <div
    class="container"
    ref="resultBox"
    @scroll="remPos"
  >
    <!-- 导航固定定位 fixed -->
    <van-nav-bar
      fixed
      title="搜索结果"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 文章列表 -->
    <van-list
      :immediate-check='false'
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      finished-text="没有更多了"
    >
      <!-- 每一项 -->
      <van-cell
        v-for="item in list"
        :key="item.art_id.toString()"
        :to="`article/${item.art_id.toString()}`"
      >
        <div class="article_item">
          <h3 class="van-ellipsis">
            {{item.title}}
          </h3>
          <div class="img_box">
            <van-image
              v-for="(img,index) in item.cover.images"
              :key="index"
              class="w100"
              fit="cover"
              :src="img"
            />
          </div>
          <div class="info_box">
            <span>{{item.aut_name}}</span>
            <span>{{item.comm_count}}评论</span>
            <span>{{item.pubdate|relTime}}</span>
          </div>
        </div>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSearchAPI } from '@/api/news'
export default {

  name: 'search-result',
  data () {
    return {
      list: [], // 搜索结果数据
      loading: false,
      finished: false,
      scrollTop: 0, // 滚动距离,
      q: null, // 关键词
      page: 1
    }
  },
  methods: {
    async onLoad () { // 获取搜索结果列表
      const { data } = await getSearchAPI(this.page, this.$route.query.q)
      // console.log(data)
      this.list.push(...data.results)
      // console.log(this.list)
      // 加载状态结束
      this.loading = false
      this.q = this.$route.query.q
      // 数据全部 加载完成
      if (this.list.length === data.total_count) {
        this.finished = true
      } else {
        this.page = this.page + 1
      }
    },
    remPos (e) { // 记录距离
      this.scrollTop = e.target.scrollTop
    }
  },
  activated () { // 组件缓存了
    if (this.q === this.$route.query.q) {
      this.$refs.resultBox.scrollTop = this.scrollTop
    } else {
      this.list = []
      this.loading = false
      this.finished = false
      this.onLoad()
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding-top: 46px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      height: 180px;
      width: 100%;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    span {
      padding-right: 10px;
    }
  }
}
</style>
